const App = getApp()
const db = wx.cloud.database()
const _ = db.command
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    textShow: false,
    // 输入框高度
    inputHeight: {
      minHeight: 150
    },
    // 按钮oading
    btnloading: false,
    // 获取详情实践任务数组
    practiceDetails: "",
    // 提交信息
    submit: {
      content: "",
      file: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this
    let practiceId = JSON.parse(decodeURIComponent(options.passData));
    console.log('传值后', practiceId);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      practiceId: practiceId,
      UserInfo: UserInfo,
    })
    that.getPracticeDetails()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  textShow() {
    that.setData({
      textShow: !that.data.textShow
    })
  },
  // input
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
    that.setData({
      'submit.content': event.detail
    })
  },
  // 添加附件
  addfile() {
    that.setData({
      btnloading: true
    })
    wx.chooseMessageFile({
      count: 10,
      type: 'all',
      success(res) {
        console.log(res);
        let data = res.tempFiles
        console.log(data);
        const uploadTasks = data.map((file, index) => {
          let cloudPath = "实践任务附件/" + that.data.practiceDetails.courseName + "/" + file.name
          return wx.cloud.uploadFile({
            cloudPath: cloudPath,
            filePath: file.path
          });
        });
        Promise.all(uploadTasks)
          .then(res => {
            let list = []
            res.forEach((item, index) => {
              list.push({
                name: data[index].name,
                size: (data[index].size / 1024 / 1024).toFixed(2),
                id: item.fileID,
                type: data[index].type
              })
            })
            console.log('新增的文件', list);
            that.setData({
              ['submit.file']: list,
              btnloading: false
            })
          })
          .catch(e => {
            that.setData({
              btnloading: false
            })
            console.log(e);
          });
      },
      fail: function (res) {
        that.setData({
          btnloading: false
        })
      }
    })
  },
  // 删除附件
  removefileName(e) {
    const {
      index
    } = e.currentTarget.dataset
    console.log(index);
    let submit = that.data.submit.file
    console.log(submit.splice(index, 1));
    that.setData({
      ['submit.file']: submit
    })
  },
  // 获取任务详情
  getPracticeDetails() {
    App.toast.showLoading('加载中')
    db.collection('practice').where({
      practiceId: that.data.practiceId
    }).get({
      success: function (res) {
        App.toast.hideLoading()
        let list = res.data[0]
        console.log('获取详情', list);
        that.setData({
          practiceDetails: list,
        })
      }
    })
  },

  // 提交作业
  submit() {
    // 校验实践任务是否已经终止、未开始、已截止
    let practice = that.data.practiceDetails
    if (practice.practiceSwitch === false) {
      App.toast.showToast('实践任务已终止,成员不可进行操作。')
      return
    }
    let submit = that.data.submit
    console.log('submit', submit);
    if (submit.content == '' && submit.file == '') {
      App.toast.showToast('不能提交空作业')
      return
    }

    wx.showModal({
      title: '提示',
      content: '作业仅能提交一次',
      success(res) {
        if (res.confirm) {

          App.toast.showLoading('提交中')
          db.collection('practice').where(_.and([{
              practiceId: _.eq(that.data.practiceId)
            },
            {
              courseMember: {
                account: _.in([that.data.UserInfo.account])
              }
            },
            {
              courseMember: {
                Submit: false
              }
            }
          ])).update({
            data: {
              'courseMember.$.content': submit.content,
              'courseMember.$.file': submit.file,
              'courseMember.$.Submit': true,
              submitTime: Date.now()
            },
            success: function (res) {
              App.toast.hideLoading()
              console.log('提交成功', res);
              App.toast.showToast('提交成功')
              setTimeout(() => {
                App.route.relBack('/pages/students/details/index')
              }, 1500)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

})